<template>
  <PageContainer>
    <Header title="管理员" />
    <view class="hb-p-4">
      <view class="hb-bg-white hb-p-3 hb-rounded-xl hb-box-shadow-base">
        <TmText label="管理员" _class="hb-font-bold hb-mb-2" :font-size="28" />
        <TmText label="管理员可以协助一起管理圈子" color="#999996" :font-size="24" />
        <DataItem v-for="item in dataList" :key="item.id" :data="item" @delete="showDelModal" />
      </view>
      <TmModal
        v-model:show="modalVisible"
        title="删除管理员"
        :height="300"
        :follow-theme="false"
        cancel-text="取消"
        cancel-color="#969799"
        ok-color="#EA5E0E"
        ok-text="确认删除"
        @ok="handleDelete"
      >
        <view class="hb-text-sm hb-text-[#333] hb-text-center">
          <text>确定要删除管理员“</text>
          <text class="hb-text-primary">{{ getItem?.displayName }}</text>
          <text>”吗？删除后，该用户将无法再协助你管理圈子</text>
        </view>
      </TmModal>

      <BottomSubmit submit-btn-label="添加管理员" @submit="handleAddAdmin" />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* circleAdminManagement 管理员 */
  import { addCircleAdmin, circleAdminList, removeCircleAdmin } from '@/api/contact';
  import DataItem from './components/DataItem.vue';
  import { CircleMemberListResult } from '@/api/contact/types';
  import { CircleAdminManagement } from '@/router/types/modules';
  import { Toast } from '@/utils';

  const dataList = ref<CircleMemberListResult[]>([]);

  const circlesId = ref<number>(0);
  const modalVisible = ref<boolean>(false);

  const getDataList = async () => {
    const res = await circleAdminList({ id: circlesId.value });
    dataList.value = res;
    return res;
  };

  let success: CircleAdminManagement['success'];
  customOnload<'circleAdminManagement'>((op) => {
    circlesId.value = op.id;
    getDataList();
    success = op.success;
  });

  const selected = ref<number>();
  const getItem = computed(() => dataList.value.find((item) => item.id === selected.value));

  const showDelModal = (id: number) => {
    selected.value = id;
    modalVisible.value = true;
  };

  const handleDelete = async () => {
    await removeCircleAdmin({ id: selected.value! });
    Toast('删除成功');
    dataList.value = dataList.value.filter((item) => item.id !== selected.value);
    success?.(dataList.value.length);
  };

  const handleAddAdmin = () => {
    /** 添加管理员 */
    navigateTo({
      name: 'selectMembers',
      options: {
        id: circlesId.value,
        selected: dataList.value.map((item) => item.id),
        type: 'admin',
        success: async (data) => {
          uni.showLoading({ title: '添加中...' });
          await addCircleAdmin({
            circleId: circlesId.value,
            memberIds: data.map((item) => item.id),
          });
          const res = await getDataList();
          success?.(res.length > 0 ? res.length - 1 : 0);
          uni.hideLoading();
        },
      },
    });
  };
</script>

<style lang="scss" scoped></style>
